﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Infrastructure
{
    /// <summary>
    /// MD5处理
    /// </summary>
    public class MD5Handle
    {
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public static string Encryption(string strContent)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strContent);
            bytes = md5.ComputeHash(bytes);
            md5.Clear();

            string strValue = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                strValue += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
            }

            return strValue.PadLeft(32, '0');
        }

        /// <summary>
        /// 匹配加密内容
        /// </summary>
        /// <param name="sourcestrt">源内容</param>
        /// <param name="encryptContent">加密内容</param>
        /// <returns></returns>
        public static bool MatchEncrpytContent(string sourceContent, string encryptContent)
        {
            return string.Equals(encryptContent, Encryption(sourceContent));
        }

        /// <summary>
        /// 获取MD5签名
        /// </summary>
        /// <param name="encypStr">待加密的字符</param>
        /// <param name="charset">字符编码格式</param>
        /// <param name="toUpper">是否大写</param>
        /// <returns></returns>
        public static string GetMD5(string encypStr, string charset = "utf-8", bool toUpper = false)
        {
            string retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "");
            if (toUpper) { retStr = retStr.ToUpper(); }
            return retStr;
        }
    }
}
